package itsm.isperp.module.controller;

import itsm.isperp.framework.security.encoding.MD5Helper;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.utils.LoginUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bouncycastle.jce.provider.JDKMessageDigest.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-8-27
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("/sso")
public class LoginSSOController {

	@Autowired
	AppUserService appUserService;

	@RequestMapping(value = "")
	public ModelAndView main(String error, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes)
			throws Exception {
		ModelAndView mv = new ModelAndView("main");
		mv.setViewName("redirect:/main");
		return mv;
	}
	
	@RequestMapping(value = "login")
	@ResponseBody
	public ModelAndView login(String error, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes)
			throws Exception {
		ModelAndView mv = new ModelAndView();
		String userName=request.getParameter("u");
		String token=request.getParameter("tk");
		
		Date now=new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		String todayStr=formatter.format(now);
		String tToken=userName+todayStr;
		tToken=MD5Helper.encrypt(tToken);
		
		try
		{
		  if(token!=null && tToken.equals(token.toLowerCase()) && !userName.equals("admin"))
		  {
		    LoginUtils.login(userName, "单点登录", request, response);
	      mv.setViewName("redirect:/main?noHeader=t");
		  }else
		  {
		    mv.setViewName("redirect:/main/login?error=true");
		  }
			
		}catch(Exception ex)
		{
			mv.setViewName("redirect:/main/login?error=locked");
		}
		
		return mv;
	}
}
